package double_pointer;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-12-03
 * Time: 9:37
 */
public class SortColors {
    public static void sortColors1(int[] nums) {
        int low = 0;
        int fast = 0;
        while (fast < nums.length) {
            if (nums[fast] == 0) {
                swap(nums, low, fast);
                low++;
            }
            fast++;
        }
        fast = low;
        while (fast < nums.length) {
            if(nums[fast] == 1) {
                swap(nums, low, fast);
                low++;
            }
            fast++;
        }
    }

    private static void swap(int[] nums, int low, int fast) {
        int tmp = nums[low];
        nums[low] = nums[fast];
        nums[fast] = tmp;
    }

    public static void sortColors2(int[] nums) {
        int p0 = 0;
        int p1 = 0;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] == 0) {
                swap(nums, i, p0);
                if (p0 < p1) {
                    swap(nums, i, p1);
                }
                p1++;
                p0++;
            } else if (nums[i] == 1) {
                swap(nums, p1, i);
                p1++;
            }
        }
    }

    public static void main(String[] args) {
        sortColors(new int[]{2,0,2,1,1,0});
    }

    public static void sortColors(int[] nums) {
        int p0 = 0;
        int n = nums.length;
        int p2 = n - 1;
        for (int i = 0; i <= p2; i++) {
            while (i <= p2 && nums[i] == 2) {
                swap(nums, i, p2);
                p2--;
            }
            if (nums[i] == 0) {
                swap(nums, i, p0);
                p0++;
            }
        }
    }
}
